<?php
/**
 * Created by
 * User: xuguopeng
 * Date: 7/10/21
 * Time: 10:35 PM
 * Effect: 商家活动类
 */

namespace app\api\controller\v1;


use app\api\model\GrActivity as GrActivityModel;

use app\api\model\GrActivityImg;
use app\api\model\User;
use LinCmsTp5\exception\ParameterException;
use think\Db;

class GrActivity
{
    /**
     * 获取全部
     */
    public function getDataAll()
    {
        return GrActivityModel::where('status',2)->with('imgs.img')->order('id desc')->select()->toArray();
    }

    /**
     * 获取列表
     * @validate('PagingParameter')
     * @auth('个人活动','个人活动管理')
     */
    public function getDataList($title, $status,$page,$limit)
    {
        $where = [];
        if($title) {
            $where[] = ['title','like','%'.$title.'%'];
        }
        if($status) {
            $where[] = ['status','eq',$status];
        }
        $query = GrActivityModel::where($where)->with('imgs.img')->order('order_sort desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->each(function (&$item){
            if($item['num_status'] == 0) {
                $item['num_status_name'] = '无限制';
            }else {
                $item['num_status_name'] = '有限制';
            }
            if($item['status'] == 1) {
                $item['status_name'] = '审核中';
            }elseif($item['status'] == 2) {
                $item['status_name'] = '审核通过';
            }elseif($item['status'] == 3) {
                $item['status_name'] = '审核不通过';
            }
            if($item['recommend'] == 0) {
                $item['recommend_name'] = '不推荐首页';
            } elseif($item['recommend'] == 1) {
                $item['recommend_name'] = '推荐首页';
            }
            $item['user'] = User::where('openid',$item['openid'])->find();
        })->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return GrActivityModel::where('id',$id)->with('imgs.img')->find();
    }

    /**
     * 审核通过信息
     * @validate('CheckGrActivity')
     */
    public function updateData($id,$recommend,$status,$status_con,$order_sort)
    {
            if($status == 2) {
                $status_con = '';
            }
            $info = GrActivityModel::get($id);
            if ($info) {
                $info->recommend = $recommend;
                $info->order_sort = $order_sort;
                $info->status = $status;
                $info->status_con = $status_con;
                $info->save();
            }
            return writeJson(202, [], '操作成功！');
    }

    /**
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        GrActivityModel::destroy($id);
        GrActivityImg::destroy(['activity_id'=>$id]);
        return writeJson(203, [], '删除成功！');
    }

}